package com.yatong.commons.shiro;

import com.yatong.entity.SysRole;
import com.yatong.entity.SysUser;
import com.yatong.service.SysRoleService;
import com.yatong.service.SysUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.*;

public class ShrioRealm extends AuthorizingRealm {

    @Autowired
    SysUserService sysUserService;
    @Autowired
    SysRoleService sysRoleService;

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限认证方法：MyShiroRealm.doGetAuthenticationInfo()");
        SysUser sysUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
//        Integer userId = sysUser.getId();
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();


        Set<String> roleNameSet = new HashSet<>();
        Set<String> permissionSet = new HashSet<>();

        //角色加入AuthorizationInfo认证对象
        String[] split = sysUser.getRoleid().split(",");
        for (String roleId : split) {
//            List<String> permissions = shiroFactory.findPermissionsByRoleId(roleId);
//            if (permissions != null) {
//                for (String permission : permissions) {
//                    if (ToolUtil.isNotEmpty(permission)) {
//                        permissionSet.add(permission);
//                    }
//                }
//            }动态菜单
            SysRole sysRole = sysRoleService.queryById(Integer.parseInt(roleId));
            roleNameSet.add(sysRole.getTips());
        }

//        info.addStringPermissions(permissionSet);//添加权限
        info.addRoles(roleNameSet);
        return info;
    }

    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     *
     * @param authcToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        System.out.println("身份认证方法：ShrioRealm.doGetAuthenticationInfo()");
        if (authcToken.getPrincipal() == null) {
            return null;
        }
        UsernamePasswordToken token = (UsernamePasswordToken)authcToken;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("username", token.getUsername());
        SysUser sysUser = null;
        // 从数据库获取对应用户名密码的用户
        sysUser = sysUserService.queryByName(token.getUsername());
        if (null == sysUser) {
            throw new AccountException("帐号或密码不正确！");
        }else if(sysUser.getStatus()==0){
            throw new DisabledAccountException("帐号已经禁止登录！");
        }else{
            //再次可以处理，更新登录时间 last login time
        }
        return new SimpleAuthenticationInfo(sysUser, sysUser.getPassword(), getName());
    }
}
